﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using PPI.Client;
using PPI.Client.Logic;
using PPI.Client.Logic.Delegate;
using PPI.Client.Logic.Distribution;
using PPI.Client.Logic.Inspection;
using PPI.Client.Logic.Polygon;
using PPI.Client.Logic.XML;
using PPI.Client.Utils;
using PPI.Controls.Grid;
using PPI.CRUD;
using PPI.Entities;
using PPI.Entities.Distribution;
using PPI.Entities.Enumerator;
using PPI.Entities.Inspections;
using PPI.Entities.Polygon;
using PPI.Entities.Remedy;
using PPI.Entities.Settings;
using PPI.Entities.Utility;
using PPI.Entities.XML;
using PPI.General;
using VMind.Global;
using LInspectionResult=PPI.Client.Logic.Inspection.LInspectionResult;

namespace PPI
{
    public partial class frmMain : DevComponents.DotNetBar.Office2007RibbonForm
    {
        private frmLogin m_FrmLogin;
        private frmUploadMobileDatabase m_UploadGpsDatabase;
        private frmUploadMobileDatabase m_UploadInspectionDatabase;
        private frmUploadMobileDatabase m_UploadDistributionInspectionDatabase;
        private frmUploadMobileDatabase m_UploadDistributionGPSDatabase;
        private frmDeployDatabase m_DeployDatabase;
        private frmDeployInspectionDatabase m_DeployInspectionDatabase;
        private frmDeployDistributionDatabase m_DeployDistributionDatabase;
        private EXmlOutboxBase m_SelectedGPSDatabase;
        private EXmlOutboxBase m_SelectedInspectionDatabase;
        private EXmlOutboxBase m_SelectProjectDatabase;
        private EXmlOutboxBase m_SelectedDistributionInspectionDatabase;
        private EXmlOutboxBase m_SelectedDistributionGPSDatabase;
        private List<EVendor_Visit_XMissionStructure> m_VisibleVisits;
        private frmVisitCrud m_VisitCrud;
        private frmInspectionCRUD m_InspectionCrud;
        private frmDistributionEditor m_DistributionEditor;
        private List<EUtility_Polygon> m_Polygons;
        private List<EUtility_Asset_XMissionStructure> m_Assets;
        private bool m_IsShowingPolygons;
        private frmMaps m_FrmMaps;
        private UpdateBar m_DeletegateUpdateBar;
        private ESettingsCustomInspectionKml m_CustomKml;
        private bool m_isOpenInspectionProject;
        private bool m_isOpenInspectionMobile;
        private bool m_isOpenGpsProject;
        private bool m_isOpenDistributionInspectionProject;
        private bool m_isOpenDistributionGPSProject;
        private frmSplashStartup m_FrmSplashStartup;
        private GEHelper m_GEHelper;
        private Thread m_ThreadAsyncForm;
        private Bitmap m_printerMemoryImage;
        

        public frmMain()
        {
            InitializeComponent();

            this.Visible = false;
            m_FrmSplashStartup = new frmSplashStartup();
            try
            {
                m_FrmSplashStartup.ShowDialog();
            }
            catch(Exception ex)
            {
                RegisterError.SaveError(ex);
            }


            m_FrmLogin = new frmLogin();

            m_DeletegateUpdateBar = new UpdateBar(UpdateStatusBar);

            m_GEHelper = new GEHelper(googleEarthViewPort1,m_DeletegateUpdateBar);
            m_SelectedGPSDatabase = null;
            m_SelectedInspectionDatabase = null;
            m_SelectProjectDatabase = null;
        }

        #region CLOSE GOOGLE EARTH --> WAIT --> CLOSE FORM
        bool m_GoogleEarthUnloaded = false;
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Text = "Closing application - Unloading Google Earth...";
            if (googleEarthViewPort1.IsInitialized())
                CloseGoogleEarth();

        }
        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!m_GoogleEarthUnloaded && googleEarthViewPort1.IsInitialized())
            {
                googleEarthViewPort1.Unload();
                m_GoogleEarthUnloaded = true;
                this.Text = "Closing application...";
                Thread.Sleep(3000);
            }
            else
                Application.ExitThread();
        }
        protected void CloseGoogleEarth()
        {
            ClearGEData();
            Timer_Close_GE.Enabled = true;
            this.Text = "Closing application - Unloading Google Earth...";
        }
        protected void ClearGEData()
        {
            string _EmptyKML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://earth.google.com/kml/2.1\"></kml>";
            GEHelper.WriteKMLFile(_EmptyKML, Constants.k_Filename);
            googleEarthViewPort1.OpenKmlFile(Constants.k_Filename, 1);
        }

        #endregion CLOSE GOOGLE EARTH --> WAIT --> CLOSE FORM

        private void frmMain_Resize(object sender, EventArgs e)
        {
            googleEarthViewPort1.GoogleEarth_Resize(panelGoogleEarth.Width, panelGoogleEarth.Height);
        }

        private bool StartGoogle()
        {
            try
            {
                googleEarthViewPort1.StartGoogleApplication();
                googleEarthViewPort1.Start();
                googleEarthViewPort1.GoogleEarth_Resize(panelGoogleEarth.Width, panelGoogleEarth.Height);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        

        private void btiResetMap_Click(object sender, EventArgs e)
        {
            if (googleEarthViewPort1.IsInitialized())
                ClearGEData();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            
            if (!m_FrmLogin.IsUserLogged)
                this.Visible = false;
            else
                this.Visible = true;
            if (CheckIsInstanceAlreadyRunning())
                return;

            if (!CheckInternetConnection())
                return;

            if (!CheckGoogleEarthInstalled())
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("Google earth was not detected. Please install it", "Pole Position Desktop");
                SetupHelper.OpenInWebbrownser(Constants.K_WebGoogleEarth);
                this.Close();
            }

            m_VisibleVisits = new List<EVendor_Visit_XMissionStructure>();

            if (!m_FrmLogin.IsUserLogged)
            {
                this.Visible = false;
                this.timer_OpenedGe.Enabled = false;
                m_FrmLogin.ShowDialog();
                if (!m_FrmLogin.IsUserLogged)
                {
                    if (googleEarthViewPort1.IsInitialized())
                        googleEarthViewPort1.Unload();
                    this.Close();
                }
                else
                {
                    LCacheDataSingleton.Instance.LoggedUser = m_FrmLogin.LoggedUser;
                    this.timer_OpenedGe.Enabled = true;
                    this.Visible = true;
                    StartGoogle();
                }
            }
            //ShowWaitCursor();
            m_SelectProjectDatabase = new EXmlOutboxProject();
            ShowApplicationTitle();
            ShowApplicationDeploymentVersion();
            m_IsShowingPolygons = false;
            m_CustomKml = LCacheDataSingleton.Instance.CustomKml;
            m_GEHelper.CustomKml = m_CustomKml;
            //ShowDefaultCursor();

            ritVendorMenu.Select();

            btnFixImages.Visible = LCacheDataSingleton.Instance.LoggedUser.Username.Trim().ToUpper() == "DERRY";
        }

        private void ShowApplicationTitle()
        {
            this.Text =
                String.Format("Pole Position Desktop for Utilities  -    Version 2.1   {0}",ConfigReader.GetInstance().ConectionMode.ToUpper());
        }

        private void ShowApplicationDeploymentVersion()
        {
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                System.Deployment.Application.ApplicationDeployment applicationDeployment = System.Deployment.Application.ApplicationDeployment.CurrentDeployment;
                Version version = applicationDeployment.CurrentVersion;
                this.Text += string.Format("  -  Published Version: v{0} . {1} . {2} . {3} ", version.Major, version.Minor, version.Build, version.Revision);
            }
        }

        private void googleEarthViewPort1_Resize(object sender, EventArgs e)
        {
            googleEarthViewPort1.GoogleEarth_Resize(panelGoogleEarth.Width, panelGoogleEarth.Height);
        }

        private void panelGoogleEarth_Resize(object sender, EventArgs e)
        {
            googleEarthViewPort1.GoogleEarth_Resize(panelGoogleEarth.Width, panelGoogleEarth.Height);
        }

        private bool CheckGoogleEarthInstalled()
        {
            try
            {
                return StartGoogle();
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        private bool CheckInternetConnection()
        {
            try
            {
                System.Net.IPHostEntry objIPHE = System.Net.Dns.GetHostByName("www.dev-poleposition.com");
               return true;
            }
            catch
            {
                // host not reachable.--> ALERT + CLOSE APPLICATION
                if (DevComponents.DotNetBar.MessageBoxEx.Show("Internet connection not available. Click Retry to check internet connection or Cancel to close application.", "Pole Position Desktop", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
                {
                    return CheckInternetConnection();
                }
                else
                {
                    this.Close();
                    Application.ExitThread();
                    return false;
                }
            }
        }
        private bool CheckIsInstanceAlreadyRunning()
        {
            if (SingleApplication.Run())
            {
                return false;
            }
            else
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("One instance of the application is already running.", "Pole Position Desktop", MessageBoxButtons.OK);
                this.Close();
                Application.ExitThread();
                return true;
            }
        }

        private void timer_OpenedGe_Tick(object sender, EventArgs e)
        {
            if (!googleEarthViewPort1.IsInitialized())
                StartGoogle();
        }

        private void buttonItemReports_Click(object sender, EventArgs e)
        {
            frmReports _Form;
            _Form = new frmReports();
            _Form.ShowDialog();
            _Form.Dispose();
        }

        private void btiUploadLocalgps_Click(object sender, EventArgs e)
        {
            if (m_UploadGpsDatabase == null)
            {
                m_UploadGpsDatabase = new frmUploadMobileDatabase();
                m_UploadGpsDatabase.OutboxBase = new EXmlOutboxGPS();
                m_UploadGpsDatabase.ShowDialog();
            }else
            {
                m_UploadGpsDatabase.Visible = true;
            }
        }

        private void btiUploadLocalInspection_Click(object sender, EventArgs e)
        {
           if(m_UploadInspectionDatabase == null)
           {
               m_UploadInspectionDatabase = new frmUploadMobileDatabase();
               m_UploadInspectionDatabase.OutboxBase = new EXmlOutboxInspection();
               m_UploadInspectionDatabase.ShowDialog();

           }
           else
           {
               m_UploadInspectionDatabase.Visible = true;
           }
        }

        private void btiUploadLocalDistribution_Click(object sender, EventArgs e)
        {
            if (m_UploadDistributionInspectionDatabase == null)
            {
                m_UploadDistributionInspectionDatabase = new frmUploadMobileDatabase();

                m_UploadDistributionInspectionDatabase.OutboxBase = new EXmlOutboxDistributionInspection();
                m_UploadDistributionInspectionDatabase.ShowDialog();

            }
            else
            {
                m_UploadDistributionInspectionDatabase.Visible = true;
            }
        }

        private void btiUploadLocalDistributionGPS_Click(object sender, EventArgs e)
        {
            if (m_UploadDistributionGPSDatabase == null)
            {
                m_UploadDistributionGPSDatabase = new frmUploadMobileDatabase();

                m_UploadDistributionGPSDatabase.OutboxBase = new EXmlOutboxDistributionGPS();
                m_UploadDistributionGPSDatabase.ShowDialog();

            }
            else
            {
                m_UploadDistributionGPSDatabase.Visible = true;
            }
        }

        private void btiDeploySDgps_Click(object sender, EventArgs e)
        {
            if(m_DeployDatabase == null)
                m_DeployDatabase = new frmDeployDatabase();
            m_DeployDatabase.ShowDialog();
        }
        
        private void btiDeploySDInspection_Click(object sender, EventArgs e)
        {
            if (m_DeployInspectionDatabase == null)
            {
                m_DeployInspectionDatabase = new frmDeployInspectionDatabase();
            }
            m_DeployInspectionDatabase.ShowDialog();

        }

        private void btnDistributionDeploy_Click(object sender, EventArgs e)
        {
            if (m_DeployDistributionDatabase == null)
                m_DeployDistributionDatabase = new frmDeployDistributionDatabase();

            m_DeployDistributionDatabase.ShowDialog();
        }

        private void btiCopyFromSDgps_Click(object sender, EventArgs e)
        {
            frmCopyMobileDatabase _Form = new frmCopyMobileDatabase();
            if(_Form.ShowDialog() == DialogResult.OK)
            {
                switch (_Form.SelectedOutbox.DatabaseType)
                {
                    case DatabaseTypes.GPS:
                        m_SelectedGPSDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.Inspection:
                        m_SelectedInspectionDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.DistributionGPS:
                        m_SelectedDistributionGPSDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.DistributionInspection:
                        m_SelectedDistributionInspectionDatabase = _Form.SelectedOutbox;
                        break;
                }
            }
        }

        private void btiCopyFromSDInspection_Click(object sender, EventArgs e)
        {
            btiCopyFromSDgps_Click(sender, e);
        }

        private void btiCopyFromSDDistribution_Click(object sender, EventArgs e)
        {
            frmCopyMobileDatabase _Form = new frmCopyMobileDatabase(true);
            if (_Form.ShowDialog() == DialogResult.OK)
            {
                switch (_Form.SelectedOutbox.DatabaseType)
                {
                    case DatabaseTypes.GPS:
                        m_SelectedGPSDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.Inspection:
                        m_SelectedInspectionDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.DistributionGPS:
                        m_SelectedDistributionGPSDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.DistributionInspection:
                        m_SelectedDistributionInspectionDatabase = _Form.SelectedOutbox;
                        break;
                }
            }
        }

        private void btiOpenLocalGpsDatabase_Click(object sender, EventArgs e)
        {
            frmOutbox _Form = new frmOutbox();
            _Form.OutboxBase = new EXmlOutboxGPS();
            if (_Form.ShowDialog() == DialogResult.OK)
            {
                switch (_Form.SelectedOutbox.DatabaseType)
                {
                    case DatabaseTypes.GPS:
                        m_SelectedGPSDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.Inspection:
                        m_SelectedInspectionDatabase = _Form.SelectedOutbox;
                        break;

                }
                try
                {
                    ViewGPS();
                }
                catch (Exception ex)
                {
                    RegisterError.SaveError(ex);
                }
            }
        }

        private void btiOpenInspection_Click(object sender, EventArgs e)
        {
            frmOutbox _Form = new frmOutbox();
            _Form.OutboxBase = new EXmlOutboxInspection();
            if (_Form.ShowDialog() == DialogResult.OK)
            {
                switch (_Form.SelectedOutbox.DatabaseType)
                {
                    case DatabaseTypes.GPS:
                        m_SelectedGPSDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.Inspection:
                        m_SelectedInspectionDatabase = _Form.SelectedOutbox;
                        break;

                }

                try
                {
                    btiInspectionProjectMap.Enabled = true;
                    ViewInspection();
                }
                catch (Exception ex)
                {
                    RegisterError.SaveError(ex);
                }
            }
        }

        private void btnOpenLocalDBDistribution_Click(object sender, EventArgs e)
        {
            frmOutbox _Form = new frmOutbox();
            _Form.OutboxBase = new EXmlOutboxInspection();
            if (_Form.ShowDialog() == DialogResult.OK)
            {
                switch (_Form.SelectedOutbox.DatabaseType)
                {
                    case DatabaseTypes.GPS:
                        m_SelectedGPSDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.Inspection:
                        m_SelectedInspectionDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.DistributionGPS:
                        m_SelectedDistributionGPSDatabase = _Form.SelectedOutbox;
                        break;
                    case DatabaseTypes.DistributionInspection:
                        m_SelectedDistributionInspectionDatabase = _Form.SelectedOutbox;
                        break;
                }

                try
                {
                    //btiInspectionProjectMap.Enabled = true;
                    if (_Form.SelectedOutbox.DatabaseType == DatabaseTypes.DistributionInspection)
                        ViewDistributionInspection();
                    else if (_Form.SelectedOutbox.DatabaseType == DatabaseTypes.DistributionGPS)
                        ViewDistributionGPS();
                }
                catch (Exception ex)
                {
                    RegisterError.SaveError(ex);
                }
            }
        }

        private bool CheckDatabaseWasOpened (EXmlOutboxBase xmlBase)
        {
            if (xmlBase.Id == null) 
                return false;

            LXmlOutbox serviceOutbox = new LXmlOutbox(xmlBase);
            return serviceOutbox.GetOutboxById(xmlBase.Id).IsOpened;
            
        }

        private bool CheckDatabaseWasUploaded(EXmlOutboxBase xmlBase)
        {
            if (xmlBase.Id == null)
                return false;

            LXmlOutbox serviceOutbox = new LXmlOutbox(xmlBase);
            return serviceOutbox.GetOutboxById(xmlBase.Id).IsDataUploaded;

        }

        private void gridInspection1_ClickedDelete(object sender, PPI.Controls.Grid.GridBaseEventArgs e)
        {
            try
            {
                if (CheckDatabaseWasOpened(gridInspection1.OutboxBase))
                {
                    MessageBox.Show("Current database has alredy started uploading");
                    return;
                }



                if (gridInspection1.CurrentVisits != null)
                {
                    EInspectionResult tmpResult = gridInspection1.CurrentVisits.Find(delegate(EInspectionResult r) { return r.Id == e.SelectedId; });
                    string _Message = "Inspection Result id: " + tmpResult.Id + " will be deleted from server database. Are you sure you want to delete this inspection?";
                    if (MessageBox.Show(_Message, "Delete asset", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        LInspectionResult.DeleteMobile(tmpResult, gridInspection1.OutboxBase.ConnectionString);
                        MessageBox.Show("Deleted Succesfull");
                        gridInspection1.Datagrid.Rows.Remove(e.SelectedRow);
 
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridDistribution_ClickedDelete(object sender, TreeGridBaseEventArgs e)
        {
            try
            {
                if (CheckDatabaseWasOpened(treeGridDistribution.MobileBase))
                {
                    MessageBox.Show("Current database has alredy started uploading");
                    return;
                }

                if (CheckDatabaseWasUploaded(treeGridDistribution.MobileBase))
                {
                    MessageBox.Show("Current database has already uploaded");
                    return;
                }

                if (treeGridDistribution.Poles != null)
                {
                    EDistributionPole poleClicked = treeGridDistribution.Poles.Find(delegate(EDistributionPole pole) { return pole.Id == e.ParentId; });
                    string _Message = "Distribution Pole id: " + poleClicked.Id + " will be deleted from database. Are you sure you want to delete this pole?";

                    if (MessageBox.Show(_Message, "Delete ", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        if (poleClicked.isProjectPole)
                            LPole.Delete(poleClicked);

                        LPole.Delete(treeGridDistribution.MobileBase.ConnectionString, poleClicked);
                        MessageBox.Show("Deleted Succesfull");

                        treeGridDistribution.DeletePole(poleClicked);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridDistribution_ClickedEdit(object sender, TreeGridBaseEventArgs e)
        {
            try
            {
                EDistributionPole poleClicked = treeGridDistribution.Poles.Find(delegate(EDistributionPole pole) { return pole.Id == e.ParentId; });

                if (m_DistributionEditor == null)
                    m_DistributionEditor = new frmDistributionEditor();

                frmSplashDistribution frmSplash = new frmSplashDistribution();
                frmSplash.Pole = poleClicked;
                frmSplash.ShowDialog(this);

                m_DistributionEditor.m_OutboxBase = treeGridDistribution.MobileBase;
                m_DistributionEditor.Pole = poleClicked;

                m_DistributionEditor.ShowDialog();

                treeGridDistribution.UpdatePole(m_DistributionEditor.Pole);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }            
        }

        private void gridDistribution_ClickedEdit (object sender, GridBaseEventArgs e)
        {
            try
            {
                if (CheckDatabaseWasOpened(gridDistribution.OutboxBase))
                {
                    MessageBox.Show("Current database has already started uploading");
                    return;
                }

                if (CheckDatabaseWasUploaded(gridDistribution.OutboxBase))
                {
                    MessageBox.Show("Current database has already uploaded");
                    return;
                }

                if (m_DistributionEditor == null)
                    m_DistributionEditor = new frmDistributionEditor();

                m_DistributionEditor.m_OutboxBase = gridDistribution.OutboxBase;
                m_DistributionEditor.Pole = gridDistribution.CurrentPoles.Find(delegate(EDistributionPole pole) { return pole.Id == e.SelectedId; });

                if (m_DistributionEditor.ShowDialog() == DialogResult.OK)
                {
                    //if (gridInspection1.OutboxBase.DatabaseType == DatabaseTypes.Project)
                    //    ViewProjectInspection();
                    //else
                    //    ViewInspection();
                }
                gridDistribution.LoadPoles(m_SelectedDistributionInspectionDatabase.ConnectionString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void gridDistribution_ClickedDelete(object sender, GridBaseEventArgs e)
        {
            try
            {
                if (CheckDatabaseWasOpened(gridDistribution.OutboxBase))
                {
                    MessageBox.Show("Current database has alredy started uploading");
                    return;
                }

                if (CheckDatabaseWasUploaded(gridDistribution.OutboxBase))
                {
                    MessageBox.Show("Current database has already uploaded");
                    return;
                }

                if (gridDistribution.CurrentPoles != null)
                {
                    EDistributionPole selectedPole = gridDistribution.CurrentPoles.Find(delegate(EDistributionPole pole) { return pole.Id == e.SelectedId; });
                    string _Message = "Distribution Pole id: " + selectedPole.Id + " will be deleted from database. Are you sure you want to delete this pole?";
                    
                    if (MessageBox.Show(_Message, "Delete ", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        LPole.Delete(gridDistribution.OutboxBase.ConnectionString, selectedPole);
                        MessageBox.Show("Deleted Succesfull");
                        gridDistribution.Datagrid.Rows.Remove(e.SelectedRow);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void gridDistributionGPS_ClickedEdit(object sender, GridBaseEventArgs e)
        {
            try
            {
                if (CheckDatabaseWasOpened(gridDistributionGPS.OutboxBase))
                {
                    MessageBox.Show("Current database has already started uploading");
                    return;
                }

                if (CheckDatabaseWasUploaded(gridDistributionGPS.OutboxBase))
                {
                    MessageBox.Show("Current database has already uploaded");
                    return;
                }

                if (m_DistributionEditor == null)
                    m_DistributionEditor = new frmDistributionEditor();

                m_DistributionEditor.m_OutboxBase = gridDistributionGPS.OutboxBase;
                m_DistributionEditor.Pole = gridDistributionGPS.CurrentPoles.Find(delegate(EDistributionPole pole) { return pole.Id == e.SelectedId; });

                if (m_DistributionEditor.ShowDialog() == DialogResult.OK)
                {
                    //if (gridInspection1.OutboxBase.DatabaseType == DatabaseTypes.Project)
                    //    ViewProjectInspection();
                    //else
                    //    ViewInspection();
                }
                gridDistributionGPS.LoadPoles(m_SelectedDistributionGPSDatabase.ConnectionString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void gridDistributionGPS_ClickedDelete(object sender, GridBaseEventArgs e)
        {
            try
            {
                if (CheckDatabaseWasOpened(gridDistributionGPS.OutboxBase))
                {
                    MessageBox.Show("Current database has alredy started uploading");
                    return;
                }

                if (CheckDatabaseWasUploaded(gridDistribution.OutboxBase))
                {
                    MessageBox.Show("Current database has already uploaded");
                    return;
                }

                if (gridDistributionGPS.CurrentPoles != null)
                {
                    EDistributionPole selectedPole = gridDistributionGPS.CurrentPoles.Find(delegate(EDistributionPole pole) { return pole.Id == e.SelectedId; });
                    string _Message = "Distribution Pole id: " + selectedPole.Id + " will be deleted from database. Are you sure you want to delete this pole?";

                    if (MessageBox.Show(_Message, "Delete ", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        LPole.Delete(gridDistributionGPS.OutboxBase.ConnectionString, selectedPole);
                        MessageBox.Show("Deleted Succesfull");
                        gridDistributionGPS.Datagrid.Rows.Remove(e.SelectedRow);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void gridInspection1_ClickedEdit(object sender, GridBaseEventArgs e)
        {
            try
            {

                if (CheckDatabaseWasOpened(gridInspection1.OutboxBase))
                {
                    MessageBox.Show("Current database has alredy started uploading");
                    return;
                }
                if (m_InspectionCrud == null)
                {
                    m_InspectionCrud = new frmInspectionCRUD();
                }
                m_InspectionCrud.Database = gridInspection1.OutboxBase;
                m_InspectionCrud.Inspection = gridInspection1.CurrentVisits.Find(delegate(EInspectionResult r) { return r.Id == e.SelectedId; }).Inspection;

                if (m_InspectionCrud.ShowDialog() == DialogResult.OK)
                {
                    if (gridInspection1.OutboxBase.DatabaseType == DatabaseTypes.Project)
                        ViewProjectInspection();
                    else
                        ViewInspection();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void btiProjectGridInspection_Click(object sender, EventArgs e)
        {
            /* 
            frmDownloadProjectDatabase frm = new frmDownloadProjectDatabase();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
            */
                try
                {
                    ViewProjectInspection();
                    tabControlMainContainer.SelectedTab = tabInspection;
                }
                catch (Exception ex)
                {
                    RegisterError.SaveError(ex);
                }

            //}
        }

        private void btiProjectGridgps_Click(object sender, EventArgs e)
        {

            /* NEEDED TO COMMENT THIS. THE DOWNLOAD IS MADE THROUGH THE RECEIVE UPDATE
            frmDownloadProjectDatabase frm = new frmDownloadProjectDatabase();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
             * */
                try
                {
                    ViewProjectGPS();
                    tabControlMainContainer.SelectedTab = tabGridgps;
                }
                catch (Exception ex)
                {
                    RegisterError.SaveError(ex);
                }
            //}

        }

        private void btiProjectDistributionInspection_Click(object sender, EventArgs e)
        {
            try
            {
                ViewDistributionInspectionProject();
                tabControlMainContainer.SelectedTab = tabDistributionInspection;
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void btiProjectDistributionGPS_Click(object sender, EventArgs e)
        {
            try
            {
                ViewDistributionGPSProject();
                tabControlMainContainer.SelectedTab = tabDistributionInspection;
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void ViewDistributionInspectionProject()
        {
            if (m_SelectProjectDatabase != null && File.Exists(m_SelectProjectDatabase.ConnectionString))
            {
                m_Assets = null;
                tabDistributionInspection.Visible = true;
                treeGridDistribution.Visible = true;
                gridDistribution.Visible = false;
                treeGridDistribution.MobileBase = m_SelectProjectDatabase;
                try
                {
                    ShowWaitCursor();
                    m_isOpenDistributionInspectionProject = true;
                    treeGridDistribution.DistributionType = DistributionType.Inspection;
                    treeGridDistribution.LoadStructures(m_SelectProjectDatabase.ConnectionString);
                    //btiProjectMapgps.Enabled = true;
                    btiUtilityViewProjectMap.Enabled = true;
                    //m_VisibleVisits = treeGridProjectGPS.Structures;
                    ShowDefaultCursor();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    RegisterError.SaveError(ex);
                }
            }
            else
            {
                tabDistributionInspection.Visible = false;
                m_GEHelper.Clean();
            }
        }


        private void ViewDistributionGPSProject()
        {
            if (m_SelectProjectDatabase != null && File.Exists(m_SelectProjectDatabase.ConnectionString))
            {
                m_Assets = null;
                tabDistributionGPS.Visible = true;
                treeGridDistributionGPS.Visible = true;
                gridDistributionGPS.Visible = false;
                treeGridDistributionGPS.MobileBase = m_SelectProjectDatabase;
                try
                {
                    ShowWaitCursor();
                    m_isOpenDistributionGPSProject = true;
                    treeGridDistributionGPS.DistributionType = DistributionType.GPS;
                    treeGridDistributionGPS.LoadStructures(m_SelectProjectDatabase.ConnectionString);
                    //btiProjectMapgps.Enabled = true;
                    btiUtilityViewProjectMap.Enabled = true;
                    //m_VisibleVisits = treeGridProjectGPS.Structures;
                    ShowDefaultCursor();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    RegisterError.SaveError(ex);
                }
            }
            else
            {
                tabDistributionGPS.Visible = false;
                m_GEHelper.Clean();
            }
        }

        private void ViewProjectGPS()
        {
            if (m_SelectProjectDatabase != null && File.Exists(m_SelectProjectDatabase.ConnectionString))
            {
                m_Assets = null;
                tabGridgps.Visible = true;
                treeGridProjectGPS.MobileBase = m_SelectProjectDatabase;
                try
                {
                    ShowWaitCursor();
                    m_isOpenGpsProject = true;
                    treeGridProjectGPS.LoadStructures(m_SelectProjectDatabase.ConnectionString);
                    btiProjectMapgps.Enabled = true;
                    btiUtilityViewProjectMap.Enabled = true;
                    m_VisibleVisits = treeGridProjectGPS.Structures;
                    ShowDefaultCursor();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    RegisterError.SaveError(ex);
                }
            }
            else
            {
                tabGridgps.Visible = false;
                m_GEHelper.Clean();
            }
        }

        private void ViewProjectInspection()
        {
            if (m_SelectProjectDatabase != null && File.Exists(m_SelectProjectDatabase.ConnectionString))
            {
                tabInspection.Visible = true;
                treeGridProjectInspection.Visible = true;
                gridInspection1.Visible = false;
                m_Assets = null;
                treeGridProjectInspection.MobileBase = m_SelectProjectDatabase;
                try
                {
                    ShowWaitCursor();
                    m_isOpenInspectionProject = true;
                    m_isOpenInspectionMobile = false;
                    treeGridProjectInspection.LoadStructures(m_SelectProjectDatabase.ConnectionString);
                    m_GEHelper.ShowInspection = true;
                    btiInspectionProjectMap.Enabled = true;
                    ShowDefaultCursor();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    RegisterError.SaveError(ex);
                }
            }
            else
            {
                tabInspection.Visible = false;
                m_GEHelper.Clean();
            }
        }

        private void ViewGPS()
        {
            try
            {
                if (m_SelectedGPSDatabase != null && File.Exists(m_SelectedGPSDatabase.ConnectionString))
                {
                    tabGridgps.Visible = true;
                    treeGridProjectGPS.MobileBase = m_SelectedGPSDatabase;
                    treeGridProjectGPS.LoadStructures(m_SelectedGPSDatabase.ConnectionString);
                    m_VisibleVisits = treeGridProjectGPS.Structures;
                    m_GEHelper.ShowGPS = true;
                    //m_GEHelper.Visits = m_VisibleVisits;
                    //m_GEHelper.ExecuteKML();
                }
                else
                {
                    m_SelectedGPSDatabase = null;
                    tabGridgps.Visible = false;
                    m_GEHelper.Clean();
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void ViewInspection()
        {
            try
            {
                if (m_SelectedInspectionDatabase != null && File.Exists(m_SelectedInspectionDatabase.ConnectionString))
                {
                    m_isOpenInspectionProject = false;
                    m_isOpenInspectionMobile = true;
                    treeGridProjectInspection.Visible = false;
                    gridInspection1.Visible = true;
                    gridInspection1.ShowContextMenu = true;
                    gridInspection1.ShowAssociateOption = false;
                    tabInspection.Visible = true;
                    gridInspection1.OutboxBase = m_SelectedInspectionDatabase;
                    gridInspection1.LoadVisits(m_SelectedInspectionDatabase.ConnectionString);

                }
                else
                {
                    m_SelectedInspectionDatabase = null;
                    tabInspection.Visible = false;
                    m_GEHelper.Clean();
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void ViewDistributionInspection()
        {
            try
            {
                if (m_SelectedDistributionInspectionDatabase != null && File.Exists(m_SelectedDistributionInspectionDatabase.ConnectionString))
                {
                    tabDistributionInspection.Visible = true;

                    gridDistribution.Visible = true;
                    treeGridDistribution.Visible = false;
                    m_isOpenDistributionInspectionProject = false;
                    gridDistribution.ShowContextMenu = true;
                    gridDistribution.ShowAssociateOption = false;
                    gridDistribution.DistributionType = DistributionType.Inspection;
                    gridDistribution.OutboxBase = m_SelectedDistributionInspectionDatabase;
                    gridDistribution.LoadPoles(m_SelectedDistributionInspectionDatabase.ConnectionString);
                }
                else
                {
                    m_SelectedDistributionInspectionDatabase = null;
                    tabDistributionInspection.Visible = false;
                    m_GEHelper.Clean();
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void ViewDistributionGPS()
        {
            try
            {
                if (m_SelectedDistributionGPSDatabase != null && File.Exists(m_SelectedDistributionGPSDatabase.ConnectionString))
                {
                    tabDistributionGPS.Visible = true;

                    treeGridDistributionGPS.Visible = false;
                    m_isOpenDistributionGPSProject = false;
                    gridDistributionGPS.Visible = true;
                    gridDistributionGPS.ShowContextMenu = true;
                    gridDistributionGPS.ShowAssociateOption = false;
                    gridDistributionGPS.DistributionType = DistributionType.GPS;
                    gridDistributionGPS.OutboxBase = m_SelectedDistributionGPSDatabase;
                    gridDistributionGPS.LoadPoles(m_SelectedDistributionGPSDatabase.ConnectionString);
                }
                else
                {
                    m_SelectedGPSDatabase = null;
                    tabDistributionGPS.Visible = false;
                    m_GEHelper.Clean();
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void ViewMaps()
        {
            try
            {
                if (m_FrmMaps == null)
                    m_FrmMaps = new frmMaps();

                if (m_Polygons == null)
                {
                    m_Polygons = LCacheDataSingleton.Instance.Polygons;
                }
                m_FrmMaps.LoadMaps(m_Polygons);
                if (m_FrmMaps.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    double minLatitude = 0, minlongitude = 0, maxLatitude = 0, maxLongitude = 0;
                    LPolygon.GetCoordinatesLimits(m_FrmMaps.GetSelectedMaps(), ref maxLongitude, ref maxLatitude, ref minlongitude, ref minLatitude);
                    m_GEHelper.Polygons = m_FrmMaps.GetSelectedMaps();
                    m_GEHelper.ShowPolygons = true;
                    if(m_FrmMaps.ShowVisits)
                    {
                        m_GEHelper.ShowGPS = true;
                        m_GEHelper.ShowInspection = false;
                        List<EVendor_Visit_XMissionStructure> tmpListVisits;
                        tmpListVisits = LVendor_Visit_XMissionStructure.FindVisitsBetweenCoordinates(treeGridProjectGPS.Structures, maxLongitude, maxLatitude, minlongitude, minLatitude);
                        m_GEHelper.Visits = matchingVisits(tmpListVisits);
                        m_GEHelper.ExecuteKML();
                    }
                    
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
            
            
        }

        private void btiViewProjectMaps_Click(object sender, EventArgs e)
        {
            ViewFilteredInMap();
            SelectMap();
        }

        private void ViewFilteredInMap()
        {
            if (m_FrmMaps == null)
                m_FrmMaps = new frmMaps();
            if (m_Polygons == null)
            {
                m_Polygons = LCacheDataSingleton.Instance.Polygons;
            }
            m_FrmMaps.LoadMaps(m_Polygons);
            m_FrmMaps.ShowVisits = m_isOpenGpsProject;
            m_FrmMaps.ShowInspectionVisits = (m_isOpenInspectionProject || m_isOpenInspectionMobile);
            if (m_FrmMaps.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                double minLatitude = 0, minlongitude = 0, maxLatitude = 0, maxLongitude = 0;
                LPolygon.GetCoordinatesLimits(m_FrmMaps.GetSelectedMaps(), ref maxLongitude, ref maxLatitude, ref minlongitude, ref minLatitude);
                m_GEHelper.Polygons = m_FrmMaps.GetSelectedMaps();
                m_GEHelper.ShowPolygons = true;
                m_GEHelper.ShowAsset = false;
                m_GEHelper.ShowCustomKml = false;
                m_GEHelper.ShowGPS = false;
                m_GEHelper.ShowInspection = false;
                m_GEHelper.ShowInspectionStructures = false;
                if (m_FrmMaps.ShowAssets && m_SelectProjectDatabase != null)
                {
                    if (m_Assets == null && tabAsset.Visible)
                    {
                        m_Assets = treeGridAsset1.ListAssets;
                        m_GEHelper.Assets = m_Assets;
                    }
                    m_GEHelper.ShowAsset = tabAsset.Visible;
                }
                if(m_FrmMaps.ShowCustomKml)
                    m_GEHelper.ShowCustomKml = true;
                
                if (m_FrmMaps.ShowVisits)
                {
                    m_GEHelper.ShowGPS = true;
                    List<EVendor_Visit_XMissionStructure> tmpListVisits;
                    tmpListVisits = LVendor_Visit_XMissionStructure.FindVisitsBetweenCoordinates(treeGridProjectGPS.Structures, maxLongitude, maxLatitude, minlongitude, minLatitude);
                    m_GEHelper.Visits = matchingVisits(tmpListVisits);
                }
                if (m_FrmMaps.ShowInspectionVisits)
                {

                    if (treeGridProjectInspection.Structures != null && m_isOpenInspectionProject)
                    {
                        m_GEHelper.ShowInspection = false;
                        m_GEHelper.ShowInspectionStructures = true;
                        List<EInspectionStructure> tmpInspectionStructure;
                        tmpInspectionStructure =
                            LInspectionStructure.FindInpectionsBetweenCoordinates(treeGridProjectInspection.Structures,
                                                                                  maxLongitude, maxLatitude,
                                                                                  minlongitude, minLatitude);
                        m_GEHelper.InspectionStructures = mathingInspectionsStructures(tmpInspectionStructure);
                        m_GEHelper.ExecuteKML();
                        return;
                    }

                    if (gridInspection1.CurrentVisits != null && m_isOpenInspectionMobile)
                    {
                        m_GEHelper.ShowInspection = true;
                        m_GEHelper.ShowInspectionStructures = false;
                        List<EInspectionResult> tmpInspectionResults;
                        tmpInspectionResults = LInspectionResult.FindInpectionsBetweenCoordinates(gridInspection1.CurrentVisits, maxLongitude, maxLatitude, minlongitude, minLatitude);
                        m_GEHelper.InspectionResults = mathingInspections(tmpInspectionResults);
                        m_GEHelper.ExecuteKML();
                        return;
                    }
                }
                else
                    m_GEHelper.ExecuteKML();

            }
        }

        private void btiViewInspectionProjectMaps_Click(object sender, EventArgs e)
        {
            ViewFilteredInMap();
            SelectMap();
        }

        private void btiProjectMapgps_Click(object sender, EventArgs e)
        {
            ViewGpsInMap();
            SelectMap();
        }

        private void ViewGpsInMap()
        {
            m_GEHelper.ShowGPS = true;
            m_GEHelper.ShowInspection = false;
            m_GEHelper.ShowInspectionStructures = false;
            m_GEHelper.ShowPolygons = false;
            m_GEHelper.ShowCustomKml = false;
            m_GEHelper.Visits = m_VisibleVisits;
            m_GEHelper.ExecuteKML();
        }

        private void btiInspectionProjectMap_Click(object sender, EventArgs e)
        {
            ViewInspectionInMap();
            SelectMap();
        }

        private void btiDistributionInspectionProjectMap_Click(object sender, EventArgs e)
        {
            ViewDistributionInspectionInMap();
            SelectMap();
        }

        private void btiDistributionGPSProjectMap_Click(object sender, EventArgs e)
        {
            ViewDistributionGPSInMap();
            SelectMap();
        }

        private void SelectMap()
        {
            tabControlMainContainer.SelectedTab = tabMap;
        }


        private void ViewDistributionInspectionInMap()
        {
            if (m_isOpenDistributionInspectionProject) 
            {
                if (treeGridDistribution.Poles != null && treeGridDistribution.Poles.Count > 0)
                    ViewProjectDistributionInspectionInMap(treeGridDistribution.Poles);
            }
            else 
            {
                if (gridDistribution.CurrentPoles != null && gridDistribution.CurrentPoles.Count > 0)
                    ViewProjectDistributionInspectionInMap(gridDistribution.CurrentPoles);
            }
        }

        private void ViewDistributionGPSInMap()
        {
            if (m_isOpenDistributionGPSProject) 
            {
                if (treeGridDistributionGPS.Poles != null && treeGridDistributionGPS.Poles.Count > 0)
                    ViewProjectDistributionGPSInMap(treeGridDistributionGPS.Poles);
            }
            else {
                if (gridDistributionGPS.CurrentPoles != null && gridDistributionGPS.CurrentPoles.Count > 0)
                    ViewProjectDistributionGPSInMap(gridDistributionGPS.CurrentPoles);
            }
        }

        private void ViewInspectionInMap()
        {
            if(m_isOpenInspectionProject && treeGridProjectInspection.Structures != null)
            {
                ViewProjectInspectionInMap();
                return;
            }
            if(m_isOpenInspectionMobile && gridInspection1.CurrentVisits != null)
            {
                ViewLocalInspectionInMap();
                return;
            }
        }

        private void ViewProjectDistributionGPSInMap(List<EDistributionPole> poles)
        {
            m_GEHelper.ShowGPS = false;
            m_GEHelper.ShowInspection = false;
            m_GEHelper.ShowPolygons = false;
            m_GEHelper.ShowInspectionStructures = false;
            m_GEHelper.ShowCustomKml = false;
            m_GEHelper.ShowDistributionPoles = true;
            m_GEHelper.Poles = poles;
            m_GEHelper.ExecuteKML();
        }

        private void ViewProjectDistributionInspectionInMap(List<EDistributionPole> poles)
        {
            m_GEHelper.ShowGPS = false;
            m_GEHelper.ShowInspection = false;
            m_GEHelper.ShowPolygons = false;
            m_GEHelper.ShowInspectionStructures = false;
            m_GEHelper.ShowCustomKml = false;
            m_GEHelper.ShowDistributionPoles = true;
            m_GEHelper.Poles = poles;
            m_GEHelper.ExecuteKML();
        }

        private void ViewProjectInspectionInMap()
        {
            m_GEHelper.ShowGPS = false;
            m_GEHelper.ShowInspection = false;
            m_GEHelper.ShowPolygons = false;
            m_GEHelper.ShowInspectionStructures = true;
            m_GEHelper.ShowCustomKml = false;
            m_GEHelper.ShowDistributionPoles = false;
            m_GEHelper.InspectionStructures = treeGridProjectInspection.Structures;
            m_GEHelper.ExecuteKML();
        }

        private void ViewLocalInspectionInMap()
        {
            m_GEHelper.ShowGPS = false;
            m_GEHelper.ShowInspection = true;
            m_GEHelper.ShowPolygons = false;
            m_GEHelper.ShowInspectionStructures = false;
            m_GEHelper.ShowCustomKml = false;
            m_GEHelper.ShowDistributionPoles = false;
            m_GEHelper.InspectionResults = gridInspection1.CurrentVisits;
            m_GEHelper.ExecuteKML();
        }

        private List<EVendor_Visit_XMissionStructure>  matchingVisits(List<EVendor_Visit_XMissionStructure> visits)
        {
            List<EVendor_Visit_XMissionStructure> matchingVisits = visits;

            if(m_FrmMaps.GetSelectedContacts().Count > 0)
            {
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingContacts(matchingVisits, m_FrmMaps.GetSelectedContacts());
            }
            if (m_FrmMaps.GetSelectedProjects().Count > 0)
            {
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingProjects(matchingVisits, m_FrmMaps.GetSelectedProjects());
            }
            if(m_FrmMaps.GetSelectedVendors().Count > 0)
            {
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingVendors(matchingVisits, m_FrmMaps.GetSelectedVendors());
            }

            if (m_FrmMaps.GetSelectedVisitTypes().Count > 0)
            {
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingVisitTypes(matchingVisits, m_FrmMaps.GetSelectedVisitTypes());
            }
            if (m_FrmMaps.GetSelectedTopTypes().Count > 0)
            {
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingTopTypes(matchingVisits, m_FrmMaps.GetSelectedTopTypes());
            }

            if (m_FrmMaps.GetSelectedPoleClasses().Count > 0)
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingPoleClasses(matchingVisits,m_FrmMaps.GetSelectedPoleClasses());

            if (m_FrmMaps.GetSelectedPoleSpecies().Count > 0)
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingPoleSpecies(matchingVisits, m_FrmMaps.GetSelectedPoleSpecies());

            if (m_FrmMaps.GetSelectedPoleTreatments().Count > 0)
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingPoleTreatments(matchingVisits, m_FrmMaps.GetSelectedPoleTreatments());

            if (m_FrmMaps.GetSelectedPoleYears().Count > 0)
                matchingVisits = LVendor_Visit_XMissionStructure.MatchingPoleYears(matchingVisits, m_FrmMaps.GetSelectedPoleYears());

            return matchingVisits;
        }

        private List<EInspectionResult> mathingInspections(List<EInspectionResult> inspectionResults)
        {
            List<EInspectionResult> matchingInspections = inspectionResults;

            if (m_FrmMaps.GetSelectedContacts().Count > 0)
                matchingInspections = LInspectionResult.MatchingContacts(matchingInspections, m_FrmMaps.GetSelectedContacts());
            if (m_FrmMaps.GetSelectedProjects().Count > 0)
                matchingInspections = LInspectionResult.MatchingProjects(matchingInspections, m_FrmMaps.GetSelectedProjects());
            if (m_FrmMaps.GetSelectedVendors().Count > 0)
                matchingInspections = LInspectionResult.MatchingVendors(matchingInspections, m_FrmMaps.GetSelectedVendors());
            if (m_FrmMaps.GetSelectedInspectionTypes().Count > 0)
                matchingInspections = LInspectionResult.MatchingInspectionType(matchingInspections, m_FrmMaps.GetSelectedInspectionTypes());
            if (m_FrmMaps.GetSelectedResultTypes().Count > 0)
                matchingInspections = LInspectionResult.MatchingResultType(matchingInspections, m_FrmMaps.GetSelectedResultTypes());

            return matchingInspections;



        }

        private List<EInspectionStructure> mathingInspectionsStructures(List<EInspectionStructure> inspectionStructures)
        {
            List<EInspectionStructure> matchingInspections = inspectionStructures;

            if (m_FrmMaps.GetSelectedContacts().Count > 0)
                matchingInspections = LInspectionStructure.MatchingContacts(matchingInspections, m_FrmMaps.GetSelectedContacts());
            if (m_FrmMaps.GetSelectedProjects().Count > 0)
                matchingInspections = LInspectionStructure.MatchingProjects(matchingInspections, m_FrmMaps.GetSelectedProjects());
            if (m_FrmMaps.GetSelectedVendors().Count > 0)
                matchingInspections = LInspectionStructure.MatchingVendors(matchingInspections, m_FrmMaps.GetSelectedVendors());
            if (m_FrmMaps.GetSelectedInspectionTypes().Count > 0)
                matchingInspections = LInspectionStructure.MatchingInspectionType(matchingInspections, m_FrmMaps.GetSelectedInspectionTypes());
            if (m_FrmMaps.GetSelectedResultTypes().Count > 0)
                matchingInspections = LInspectionStructure.MatchingResultType(matchingInspections, m_FrmMaps.GetSelectedResultTypes());
            if(m_FrmMaps.IsElectrical())
                matchingInspections = LInspectionStructure.MatchingIsElectrical(matchingInspections, m_FrmMaps.IsElectrical());

            return matchingInspections;



        }

        private void btiUtilityViewProject_Click(object sender, EventArgs e)
        {
            ViewProjectGPS();
        }

        private void btiViewUtilityProjectMaps_Click(object sender, EventArgs e)
        {
            ViewMaps();
        }

        private void gridInspection1_ClickedAssociate(object sender, PPI.Controls.Grid.GridBaseEventArgs e)
        {
            try
            {

                if (gridInspection1.CurrentVisits != null)
                {
                    if (gridInspection1.OutboxBase.DatabaseType == DatabaseTypes.Project)
                    {
                        frmAssociateUtility form = new frmAssociateUtility();
                        form.DatabaseType = DatabaseTypes.Inspection;
                        form.IdToDuplicate = e.SelectedId;
                        form.ShowDialog();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void UpdateStatusBar(int percentage)
        {
            pbStatusMain.Value = percentage;
        }

        private void btiUtilityViewProjectGrid_Click(object sender, EventArgs e)
        {
            /* NEEDED TO COMMENT THIS. THE DOWNLOAD IS MADE THROUGH THE RECEIVE UPDATE
            frmDownloadProjectDatabase frm = new frmDownloadProjectDatabase();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
             */
                try
                {
                    ViewProjectGPS();
                }
                catch (Exception ex)
                {
                    RegisterError.SaveError(ex);
                }
            //}
        }

        private void gridInspection1_ClickedAutoDetermine(object sender, GridBaseEventArgs e)
        {
            try
            {
                frmEditStructure m_editStructure = new frmEditStructure();
                m_editStructure.InpectionResults = gridInspection1.CurrentVisits;
                m_editStructure.InspectionResult = gridInspection1.CurrentVisits.Find(delegate(EInspectionResult r) { return r.Id == e.SelectedId; });
                m_editStructure.ShowDialog();

            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void gridInspection1_ClickedEditManual(object sender, PPI.Controls.Grid.GridBaseEventArgs e)
        {



        }

        private void gridInspection1_ClickedEditWithoutImages(object sender, PPI.Controls.Grid.GridBaseEventArgs e)
        {

        }

        private void btiAutodetermine_Click(object sender, EventArgs e)
        {
            if (treeGridProjectInspection.Structures != null)
            {
                ShowAsyncDialogForm();
                List<EInspectionStructure> listStructures = LInspectionStructure.LoadProjectStructures(treeGridProjectInspection.MobileBase.ConnectionString);
                LInspectionStructure.Autodetermine(listStructures, 5, treeGridProjectInspection.MobileBase.ConnectionString);
                treeGridProjectInspection.LoadStructures(treeGridProjectInspection.MobileBase.ConnectionString);
                HideAsyncDialogForm();
            }
        }

        private void treeGridProjectGPS_ClickedEdit(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {
            try
            {
                EVendor_Visit_XMissionStructure currentVisit;

                if (CheckDatabaseWasOpened(treeGridProjectGPS.MobileBase))
                {
                    MessageBox.Show("Current database has alredy started uploading");
                    return;
                }

                if (m_VisitCrud == null)
                {
                    m_VisitCrud = new frmVisitCrud();
                }
                m_VisitCrud.OutboxBase = treeGridProjectGPS.MobileBase;
                m_VisitCrud.Visit = treeGridProjectGPS.Structures.Find(delegate(EVendor_Visit_XMissionStructure v) { return v.Id == e.ParentId; });
                m_VisitCrud.ShowImages = true;

                if (treeGridProjectGPS.MobileBase.DatabaseType == DatabaseTypes.Project)
                {
                    frmSplashVisit m_Splash = new frmSplashVisit();
                    m_Splash.VisitId = e.ParentId;
                    m_Splash.IsDownloadImages = true;
                    if(m_Splash.ShowDialog() == DialogResult.OK)
                    {
                        m_VisitCrud.Visit = m_Splash.DownloadedVisit;

                    }
                }
                
                if(m_VisitCrud.ShowDialog() == DialogResult.OK)
                {
                    if (treeGridProjectGPS.MobileBase.DatabaseType == DatabaseTypes.Project)
                        ViewProjectGPS();
                    else 
                        ViewGPS();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
			
        }

        private void treeGridProjectGPS_ClickedDelete(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {
            try
            {

                if (treeGridProjectGPS.Structures != null)
                {
                    EVendor_Visit_XMissionStructure tmpVisit = treeGridProjectGPS.Structures.Find(delegate(EVendor_Visit_XMissionStructure v) { return v.Id == e.ParentId; });
                    string _Message = "Asset id: " + tmpVisit.Id + " will be deleted from server database. Are you sure you want to delete this asset?";
                    if (MessageBox.Show(_Message, "Delete asset", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        if (treeGridProjectGPS.MobileBase.DatabaseType == DatabaseTypes.Project)
                        {
                            LVendor_Visit_XMissionStructure.Delete(tmpVisit);
                            LVendor_Visit_XMissionStructure.DeleteProject(tmpVisit, treeGridProjectGPS.MobileBase.ConnectionString);
                        }
                        else
                        {
                            LVendor_Visit_XMissionStructure.DeleteMobile(tmpVisit, treeGridProjectGPS.MobileBase.ConnectionString);
                        }
                        MessageBox.Show("Deleted Succesfull");
                        treeGridProjectGPS.RemoveNode(e.Node);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridProjectGPS_ClickedAssociate(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {
            try
            {
                if (treeGridProjectGPS.Structures != null)
                {
                    if (treeGridProjectGPS.MobileBase.DatabaseType == DatabaseTypes.Project)
                    {
                        frmAssociateUtility form = new frmAssociateUtility();
                        form.DatabaseType = DatabaseTypes.GPS;
                        form.IdToDuplicate = e.ParentId;
                        form.ConnectionString = treeGridProjectGPS.MobileBase.ConnectionString;
                        form.Latitude = ((EVendor_Visit_XMissionStructure)e.Node.DataKey).Latitude;
                        form.Longitude = ((EVendor_Visit_XMissionStructure)e.Node.DataKey).Longitude;
                        if (form.ShowDialog() == DialogResult.OK)
                            ViewProjectGPS();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridProjectGPS_ClickedEditWithoutImages(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {
            try
            {
                EVendor_Visit_XMissionStructure currentVisit;

                if (CheckDatabaseWasOpened(treeGridProjectGPS.MobileBase))
                {
                    MessageBox.Show("Current database has alredy started uploading");
                    return;
                }

                if (m_VisitCrud == null)
                {
                    m_VisitCrud = new frmVisitCrud();
                }
                m_VisitCrud.OutboxBase = treeGridProjectGPS.MobileBase;
                m_VisitCrud.Visit = treeGridProjectGPS.Structures.Find(delegate(EVendor_Visit_XMissionStructure v) { return v.Id == e.ParentId; });
                m_VisitCrud.ShowImages = false;

                if (treeGridProjectGPS.MobileBase.DatabaseType == DatabaseTypes.Project)
                {
                    frmSplashVisit m_Splash = new frmSplashVisit();
                    m_Splash.IsDownloadImages = false;
                    m_Splash.VisitId = e.ParentId;
                    if (m_Splash.ShowDialog() == DialogResult.OK)
                    {
                        m_VisitCrud.Visit = m_Splash.DownloadedVisit;
                    }
                }

                if (m_VisitCrud.ShowDialog() == DialogResult.OK)
                {
                    if (treeGridProjectGPS.MobileBase.DatabaseType == DatabaseTypes.Project)
                        ViewProjectGPS();
                    else
                        ViewGPS();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridProjectInspection_ClickedAssociate(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {
            try
            {

                if (treeGridProjectInspection.Structures != null)
                {
                    frmAssociateUtility form = new frmAssociateUtility();
                    form.DatabaseType = DatabaseTypes.Inspection;
                    form.IdToDuplicate = e.ParentId;
                    form.ConnectionString = treeGridProjectInspection.MobileBase.ConnectionString;
                    form.Latitude = ((EInspectionStructure)e.Node.DataKey).Latitude;
                    form.Longitude = ((EInspectionStructure)e.Node.DataKey).Longitude;
                    if (form.ShowDialog() == DialogResult.OK)
                        ViewProjectInspection();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridProjectInspection_ClickedDelete(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {
            if(e.Node.DataKey is EInspectionStructure)
            {
                Int32 structureId = ((EInspectionStructure) e.Node.DataKey).Id;
                string deleteMessage = string.Format("Structure id: {0} will be deleted from server database. Are you sure you want to delete this structure?", structureId);
                string deleteAllMessage = string.Format("Structure id: {0} will be deleted from server database with all poles. Are you sure you want to delete this complete structure?", structureId);
                if (structureId != Int32.MinValue && MessageBox.Show(deleteMessage, "Delete structure", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    try
                    {
                        if (structureId != Int32.MinValue &&
                            MessageBox.Show(deleteAllMessage, "Complete Delete Structure", MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) ==
                            DialogResult.Yes)
                        {
                            LInspectionStructure.DeleteWithPoles(structureId);
                        }
                        else
                        {
                            LInspectionStructure.Delete(structureId);
                        }
                        MessageBox.Show("Deleted Succesfull");
                        treeGridProjectInspection.RemoveNode(e.Node);
                    }
                    catch(Exception ex)
                    {
                        RegisterError.SaveError(ex);
                    }
                }

                
            }

        }

        private void treeGridProjectInspection_ClickedEdit(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {

            try
            {
                EInspectionStructure tmpStructure;
                EInspection tmpInspection;
                if (m_InspectionCrud == null)
                {
                    m_InspectionCrud = new frmInspectionCRUD();
                }
                m_InspectionCrud.Database = treeGridProjectInspection.MobileBase;

                frmSplashInspection m_Splash = new frmSplashInspection();
                m_Splash.InspectionId = e.ChildId;
                if (m_Splash.ShowDialog() == DialogResult.OK)
                    m_InspectionCrud.Inspection = m_Splash.Inspection;

                if (m_InspectionCrud.ShowDialog() == DialogResult.OK)
                {
                    ViewProjectInspection();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridProjectInspection_ClickedEditWithoutImages(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {

        }

        private void btiShowWorkqueue_Click(object sender, EventArgs e)
        {

            ShowWaitCursor();
            this.tabWorkQueue.Visible = true;
            this.remedyGrid1.LoadData();
            ShowDefaultCursor();
        }

        private void remedyGrid1_CellChanged(object sender, PPI.Controls.Grid.GridBaseEventArgs e)
        {
            bool isReadyToSave = true;
            if(!String.IsNullOrEmpty(e.SelectedRow.Cells[14].ErrorText))
                isReadyToSave = false;
            if(!String.IsNullOrEmpty(e.SelectedRow.Cells[15].ErrorText))
                isReadyToSave = false;

            ERemedy tmpRemedy = new ERemedy();
            tmpRemedy.Id = e.SelectedId;
            tmpRemedy.Assigned = e.SelectedRow.Cells[14].Value.ToString();
            tmpRemedy.LastAction = ConvertHelper.ToDateTime(e.SelectedRow.Cells[15].Value);
            tmpRemedy.ResolvedDate = ConvertHelper.ToDateTime(e.SelectedRow.Cells[16].Value);
            tmpRemedy.Notes = e.SelectedRow.Cells[17].Value.ToString();
            tmpRemedy.Status = new ERemedyStatus(ConvertHelper.ToInt32(e.SelectedRow.Cells[13].Value),e.SelectedRow.Cells[13].EditedFormattedValue.ToString());
            try
            {
                if(isReadyToSave)
                    LInspection.UpdateRemedy(tmpRemedy);
            }
            catch(Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void remedyGrid1_ClickLinkCell(object sender, PPI.Controls.Grid.GridBaseEventArgs e)
        {
            Int32 tmpInspectionId =ConvertHelper.ToInt32(((System.Data.DataRowView) (e.SelectedRow.DataBoundItem)).Row.ItemArray[2]); 
            try
            {
                EInspectionStructure tmpStructure;
                EInspection tmpInspection;
                if (m_InspectionCrud == null)
                {
                    m_InspectionCrud = new frmInspectionCRUD();
                }
                //m_InspectionCrud.Database = treeGridProjectInspection.MobileBase;
                frmSplashInspection m_Splash = new frmSplashInspection();
                m_Splash.InspectionId = tmpInspectionId;
                if (m_Splash.ShowDialog() == DialogResult.OK)
                    m_InspectionCrud.Inspection = m_Splash.Inspection;
                m_InspectionCrud.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void btiManageKmlgps_Click(object sender, EventArgs e)
        {
            frmManageKml kmlForm = new frmManageKml();
            kmlForm.KmlEntity = m_CustomKml;
            if (kmlForm.ShowDialog() == DialogResult.OK)
            {
                m_CustomKml = (ESettingsCustomInspectionKml)kmlForm.KmlEntity;
                m_GEHelper.CustomKml = m_CustomKml;
            }
        }

        private void btiMangeKmlInspectionProject_Click(object sender, EventArgs e)
        {
            frmManageKml kmlForm = new frmManageKml();
            kmlForm.KmlEntity = m_CustomKml;
            if (kmlForm.ShowDialog() == DialogResult.OK)
            {
                m_CustomKml = (ESettingsCustomInspectionKml)kmlForm.KmlEntity;
                m_GEHelper.CustomKml = m_CustomKml;
            }
        }

        private void ShowDefaultCursor()
        {
            this.Cursor = Cursors.Default;
            HideAsyncDialogForm();
        }

        private void ShowWaitCursor()
        {
            this.Cursor = Cursors.WaitCursor;
            ShowAsyncDialogForm();
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process internetExplorerProcess = new System.Diagnostics.Process();

            internetExplorerProcess.StartInfo.FileName = PPI.Constants.K_WEBSITEHELP;

            internetExplorerProcess.Start();
        }

        private void btiShowAssets_Click(object sender, EventArgs e)
        {
            if (File.Exists(m_SelectProjectDatabase.ConnectionString))
            {
                ShowWaitCursor();
                this.tabAsset.Visible = true;
                treeGridAsset1.LoadAssets(m_SelectProjectDatabase.ConnectionString);
                ShowDefaultCursor();
            }
        }

        private void tabControlMainContainer_TabItemClose(object sender, DevComponents.DotNetBar.TabStripActionEventArgs e)
        {
            e.Cancel = true;
            tabControlMainContainer.SelectedTab.Visible = false;
        }

        private void btiUtilityViewProjectMap_Click(object sender, EventArgs e)
        {
            ViewGpsInMap();
            SelectMap();
        }

        private void btiUtilityViewProjectMapFiltered_Click(object sender, EventArgs e)
        {
            ViewFilteredInMap();
            SelectMap();
        }

        private void treeGridProjectGPS_ClickedCreateAsset(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {
            try
            {

                if (treeGridProjectGPS.Structures != null)
                {
                    PPI.Client.Logic.Utility.LUtility_Asset_XMissionStructure.DuplicateByVisit(e.ParentId);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridProjectInspection_ClickedCreateAsset(object sender, PPI.Controls.Grid.TreeGridBaseEventArgs e)
        {
            try
            {

                if (treeGridProjectInspection.Structures != null)
                {
                    PPI.Client.Logic.Utility.LUtility_Asset_XMissionStructure.DuplicateByInspection(e.ParentId);
                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                RegisterError.SaveError(ex);
            }
        }

        private void ShowAsyncDialogForm()
        {

            try
            {
                m_ThreadAsyncForm = new Thread(StartAsyncDialogForm);
                m_ThreadAsyncForm.Start();
                
            }
            catch(Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void StartAsyncDialogForm()
        {
            try
            {
                frmAsyncDialog AsyncForm = new frmAsyncDialog();
                AsyncForm.ShowDialog();

            }catch(Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }
        private void HideAsyncDialogForm()
        {
            try
            {
                m_ThreadAsyncForm.Abort();
            }
            catch(Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void treeGridProjectGPS_ClickedExportToExcel(object sender, EventArgs e)
        {
            ExportToExcel((TreeGridBase)sender, "GPS");
        }
        //EXPORT TO EXCEL THE DISTRIBUTION INSPECTION GRID
        private void treeGridDistribution_ClickedExportToExcel(object sender, EventArgs e)
        {
            ExportToExcel((TreeGridBase)sender, "DistributionInspection");
        }
        //ELIMINAR gridDistribution_ClickedExportToExcel
        private void gridDistribution_ClickedExportToExcel(object sender, EventArgs e)
        {
            ExportToExcel((GridBase)sender, "DistributionInspection");
        }
        private void treeGridProjectInspection_ClickedExportToExcel(object sender, EventArgs e)
        {
            ExportToExcel((TreeGridBase)sender, "Inspection");
        }

        private void treeGridAsset1_ClickedExportToExcel(object sender, EventArgs e)
        {
            ExportToExcel((TreeGridBase)sender, "Asset");
        }
        /// <summary>
        /// EXPORT TO EXCEL FOR GRIDBASE
        /// </summary>
        private void ExportToExcel(GridBase grid, string text)
        {
            FileInfo newExcel = new FileInfo(PPI.Constants.K_RepositoryFolder + "\\" + PPI.Constants.TempFolderName + "\\" + text + DateTime.Now.Ticks.ToString() + ".xls");
            grid.ExportToExcel(newExcel);

            if (newExcel.Exists)
            {
                Process.Start(newExcel.FullName);
            }
        }
        /// <summary>
        /// EXPORT TO EXCEL FOR TREEGRIDBASE
        /// </summary>
        private void ExportToExcel(TreeGridBase tree, string text)
        {
            FileInfo newExcel = new FileInfo(PPI.Constants.K_RepositoryFolder + "\\" + PPI.Constants.TempFolderName + "\\" + text + DateTime.Now.Ticks.ToString()+".xls");
            tree.ExportToExcel(newExcel);

            if(newExcel.Exists)
            {
                Process.Start(newExcel.FullName);
            }
        }

        private void btiAutolinkVisit_Click(object sender, EventArgs e)
        {
             if (treeGridProjectGPS.Structures != null)
             {
                 frmAutolink form = new frmAutolink();
                 form.DatabaseType = DatabaseTypes.GPS;
                 form.Connectionstring = treeGridProjectGPS.MobileBase.ConnectionString;
                 form.ShowDialog();
             }

        }

        private void btiAutolinkInspection_Click(object sender, EventArgs e)
        {
            if (treeGridProjectInspection.Structures != null)
            {
                frmAutolink form = new frmAutolink();
                form.DatabaseType = DatabaseTypes.Inspection;
                form.Connectionstring = treeGridProjectInspection.MobileBase.ConnectionString;
                form.ShowDialog();
            }
        }

        private void treeGridProjectInspection_ClickedCreateStructure(object sender, TreeGridBaseEventArgs e)
        {
            ShowAsyncDialogForm();
            List<EInspection> listInspection = new List<EInspection>();
            listInspection.Add((EInspection)e.Node.DataKey);
            EInspectionStructure structure;
            
            structure = LInspectionStructure.CreateByInspection((EInspection) e.Node.DataKey);
            structure.Id = LInspection.CreateVisit((EInspection)e.Node.DataKey, listInspection);
            
            LInspectionStructure.Save(structure,treeGridProjectInspection.MobileBase.ConnectionString);

            foreach (EInspection inspection in structure.Inspections)
            {
                LInspection.SetStructureMobile(inspection, structure, treeGridProjectInspection.MobileBase.ConnectionString);
                LInspection.SetVisit(inspection, structure.Id);
            }

            HideAsyncDialogForm();
        }

        private void btiLogin_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            this.timer_OpenedGe.Enabled = false;
            m_FrmLogin.LoggedUser = LCacheDataSingleton.Instance.LoggedUser;
            if (m_FrmLogin.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                this.timer_OpenedGe.Enabled = false;
                if (googleEarthViewPort1.IsInitialized())
                    googleEarthViewPort1.Unload();
                this.Close();
            }
            else
            {
                this.Visible = true;
            }
        }

        private void btiEditUser_Click(object sender, EventArgs e)
        {
            frmEditUser frm = new frmEditUser();
            frm.User = LCacheDataSingleton.Instance.LoggedUser;
            frm.ShowDialog();
        }

        private void remedyGrid1_ClickedEdit(object sender, GridBaseEventArgs e)
        {
            ERemedy tmpRemedy = (ERemedy) e.RowObject;
            SelectMap();
            m_GEHelper.ExecuteKML(tmpRemedy);
        }

        private void btnFilterType_Click(object sender, EventArgs e)
        {
            frmFilterType frm = new frmFilterType();
            frm.ConnectionString = m_SelectProjectDatabase.ConnectionString;
            try
            {
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (frm.SelectedVisit != null)
                    {
                        SelectMap();
                        switch (frm.VisitType)
                        {
                            case "Inspection Structure":
                            case "Inspection Pole":
                                m_GEHelper.ExecuteKML((EInspectionStructure)frm.SelectedVisit);
                                break;
                            case "GPS Structure":
                            case "GPS Pole":
                                m_GEHelper.ExecuteKML((EVendor_Visit_XMissionStructure)frm.SelectedVisit);
                                break;
                            case "Asset":
                                m_GEHelper.ExecuteKML((EUtility_Asset_XMissionStructure)frm.SelectedVisit);
                                break;
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void btnViewBrowser_Click(object sender, EventArgs e)
        {
 
            frmFilterBrowser frm = new frmFilterBrowser();
            frm.ConnectionString = m_SelectProjectDatabase.ConnectionString;
            try
            {
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (!String.IsNullOrEmpty(frm.Direction))
                    {
                        tabBrowser.Visible = true;
                        webBrowser1.Navigate(frm.Direction);
                    }
                }
            }
            catch (Exception ex )
            {
                RegisterError.SaveError(ex);
            }
        }

        private void btiPrintBrowser_Click(object sender, EventArgs e)
        {
            CaptureBrowserScreen();
            PrintDocument pDocument = new PrintDocument();
            pDocument.PrintPage += new PrintPageEventHandler(pDocument_PrintPage);
            pDocument.EndPrint += new PrintEventHandler(pDocument_EndPrint);
            PrintPreviewDialog pr = new PrintPreviewDialog();
            pr.Document = pDocument;
            pr.Document.DefaultPageSettings.Landscape = true;
            pr.ShowDialog();
        }

        void pDocument_EndPrint(object sender, PrintEventArgs e)
        {
            if (e.PrintAction == PrintAction.PrintToPrinter)
            {
                m_printerMemoryImage.Dispose();
                m_printerMemoryImage = null;
            }
        }

        void pDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (PrinterSettings.InstalledPrinters.Count == 0)
            {
                e.Cancel = true;
                return;
            }
            
            e.Graphics.DrawImage(m_printerMemoryImage, 0, 0);
        }

        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern long BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
        
        private void CaptureBrowserScreen()
        {
            Graphics mygraphics = tabControlPanel6.CreateGraphics();
            Size s = tabControlPanel6.Size;
            m_printerMemoryImage = new Bitmap(s.Width, s.Height, mygraphics);
            Graphics memoryGraphics = Graphics.FromImage(m_printerMemoryImage);
            IntPtr dc1 = mygraphics.GetHdc();
            IntPtr dc2 = memoryGraphics.GetHdc();
            BitBlt(dc2, 0, 0, this.tabControlPanel6.Width, this.tabControlPanel6.Height, dc1, 0, 0, 13369376);
            mygraphics.ReleaseHdc(dc1);
            memoryGraphics.ReleaseHdc(dc2);
        }

        private void btnViewBrowser_PopupOpen(object sender, DevComponents.DotNetBar.PopupOpenEventArgs e)
        {
            btiPrintBrowser.Enabled = tabBrowser.Visible;
        }

        private void btiReceiveUpdates_Click(object sender, EventArgs e)
        {
            
            ShowAsyncDialogForm();
            try
            {
                if (File.Exists(Constants.K_LOCALDATABASEPROJECTPATH))
                    File.Delete(Constants.K_LOCALDATABASEPROJECTPATH);
                WebClient downloader = new WebClient();

                string deployedDatabaseUrl = LDeploy.StartDeployProject(1, "HTest", "123");
                downloader.DownloadFile(deployedDatabaseUrl, Constants.K_LOCALDATABASEPROJECTPATH);
                PPI.Mobile.General.MobileGeneral.AddAuditableColumns(Constants.K_LOCALDATABASEPROJECTPATH);
                PPI.Mobile.General.MobileGeneral.AddAuditableInspectionColumns(Constants.K_LOCALDATABASEPROJECTPATH);

                
            }
            catch(Exception ex)
            {
                RegisterError.SaveError(ex);
            }
            finally
            {
                HideAsyncDialogForm();
            }
        }

        private void ritUtilityMenu_Click(object sender, EventArgs e)
        {

        }

        private void btnFixImages_Click(object sender, EventArgs e)
        {
            frmImagesFixer frm = new frmImagesFixer();
            
            frm.ShowDialog(this);
        }

    }
}
